package qinggui.mlz.module.tag.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qinggui.mlz.module.tag.entity.Tag;
import qinggui.mlz.module.tag.mapper.TagMapper;
import qinggui.mlz.module.tag.service.TagService;

import java.util.List;

/**
 * <p>
 * 标签表 服务实现类
 * </p>
 *
 * @author qinggui
 * @since 2025-08-10
 */
@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private TagMapper tagMapper;

    /**
     * 获取标签列表
     *
     * @return List<Tag>
     */
    @Override
    public List<Tag> getAllList() {
        return tagMapper.getAllList();
    }

    /**
     * 编辑标签
     *
     * @param id   标签ID
     * @param name 标签名称
     * @return String
     */
    @Override
    public String edit(Long id, String name) {
        Tag UpdateTag = new Tag().setId(id).setName(name).setUpdateTime((int) (System.currentTimeMillis() / 1000));
        if (id != null && id > 0) {
            Tag tag = tagMapper.getById(id);
            if (tag == null) {
                throw new RuntimeException("标签不存在");
            }
            // 查看对应的标签是否存在
            Tag tagEntity = tagMapper.getOneByName(name);
            if (tagEntity != null && !tagEntity.getId().equals(id)) {
                throw new RuntimeException("标签已存在");
            }
            // 修改操作
            Integer isUpdated = tagMapper.updateTag(UpdateTag);
            if (isUpdated == 1) {
                return id.toString();
            }
            return "更新失败";
        }
        // 添加操作
        if (tagMapper.getOneByName(name) != null) {
            throw new RuntimeException("该标签已存在！");
        }
        Integer save = tagMapper.createTag(UpdateTag.setIsDeleted(0).setCreateTime((int) (System.currentTimeMillis() / 1000)));
        if (save == 1) {
            return "添加成功";
        }
        return "添加失败";
    }

    /**
     * 删除标签
     *
     * @param id 标签ID
     * @return String
     */
    @Override
    public String delete(Long id) {
        if (id != null && id > 0) {
            Tag tag = tagMapper.getById(id);
            if (tag == null) {
                throw new RuntimeException("标签不存在");
            }
            Integer isDeleted = tagMapper.deleteTag(id);
            if (isDeleted == 1) {
                return "删除成功";
            }
        }
        return "删除失败";
    }

    /**
     * 根据标签名称获取标签
     * @param tag 标签名称
     * @return  Tag
     */
    @Override
    public Tag getOneByName(String tag) {
        return tagMapper.getOneByName(tag);
    }

    @Override
    public Integer insertTag(Tag tag) {
        return tagMapper.createTag(tag);
    }

}
